// 根据 total，limit 渲染页码
// 根据 current，渲染当前页
// 

<template>
  <!-- 当总页数 小于 1，页码不显示 -->
  <div v-if="pages >= 1" class="page-content">
    <!-- 跳转到第一页 -->
    <a @click="changePage(1)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>

    <!-- 跳转到上一页 -->
    <a @click="changePage(current - 1)" :class="{ disabled: current === 1 }"
      >&lt;&lt;</a
    >

    <!-- 中间的页码，根据计算属性渲染 -->
    <a
      v-for="item in pageList"
      :key="item"
      :class="{ active: item === current }"
      @click="changePage(item)"
      >{{ item }}</a
    >

    <!-- 跳转下一页 -->
    <a @click="changePage(current + 1)" :class="{ disabled: current === pages }"
      >&gt;&gt;</a
    >

    <!-- 跳转到最后一页 -->
    <a @click="changePage(pages)" :class="{ disabled: current === pages }"
      >&gt;&gt;|</a
    >
  </div>
</template>

<script>
export default {
  props: {
    current: {
      // 当前页码
      type: Number,
      default: 1,
    },
    total: {
      // 一共多少数据
      type: Number,
      default: 0,
    },
    limit: {
      // 每页多少条数据
      type: Number,
      default: 10,
    },
    visibleNumber: {
      // 最多显示数字页码数量
      type: Number,
      default: 10,
    },
  },
  computed: {
    // 当前的总页数
    pages() {
      let num = Math.ceil(this.total / this.limit);
      return num;
    },
    // 当前最小的页数
    minPage() {
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min <= 1) {
        min = 1;
      }
      return min;
    },
    // 当前最大的页数
    maxPage() {
      let max = this.current + this.visibleNumber - 1;
      if (max >= this.pages) {
        max = this.pages;
      }
      return max;
    },
    // 获取当前页数的数组
    pageList() {
      let arr = [];
      for (let i = this.minPage; i <= this.maxPage; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  methods: {
    // 跳转指定页码
    // 抛出 chagnePage 事件，并且传递跳转的页码作为，事件参数
    changePage(num) {
      if (num <= 1) {
        num = 1;
      }
      if (num >= this.pages) {
        num = this.pages;
      }
      if (num === this.current) {
        return;
      }
      this.$emit("changePage", num);
    },
  },
};
</script>

<style scoped lang="less">
@import url(../../style/var.less);
.page-content {
  display: flex;
  justify-content: center;
  a {
    cursor: pointer;
    color: @primary;
    margin: 0 6px;
    font-size: 1.2rem;
    &.disabled {
      cursor: not-allowed;
      color: @lightWords;
    }
    &.active {
      color: @words;
      cursor: text;
    }
  }
}
</style>